package action;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.concurrent.Future;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pojo.mo.Account;
import service.AccountService;
import transport.connection.ConnectionPool;
import transport.connection.TokenFactory;
import transport.protocol.ProtocolHeader;

@Component
public class LoginAction extends BaseAction {

    private static Logger logger = Logger.getLogger(LoginAction.class);

    @Autowired
    private AccountService accountService;

    public void login(String body, Channel channel) {
        final Account account = (Account) deserializeBody(body, Account.class);
        if (accountService.isExisted(account.getUserName())) {
            if (accountService.validate(account.getUserName(), account.getPassword())) {
                loginSuccess(account, channel);
                ConnectionPool.add(account.getToken(), channel);
            } else {
                loginFailure(account, channel);
            }
        } else {
            loginFailure(account, channel);
        }
    }

    @SuppressWarnings("unchecked")
    private void loginSuccess(final Account account, final Channel channel) {
        String token = TokenFactory.generateToken();
        account.setToken(token);

        Future future = responseService.loginResponse(channel, ProtocolHeader.SUCCESS, serializeJson(account));
        future.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    logger.info(account.getUserName() + "登陆成功！");
                } else {
                    responseService.loginResponse(channel, ProtocolHeader.SUCCESS, serializeJson(account))
                        .addListener(new ChannelFutureListener() {
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if (future.isSuccess()) {
                                    logger.info(account.getUserName() + "登陆成功！");
                                }
                            }
                        });
                }
            }
        });
    }

    @SuppressWarnings("unchecked")
    private void loginFailure(final Account account, final Channel channel) {
        Future future = responseService.loginResponse(channel, ProtocolHeader.REQUEST_ERROR, "");
        future.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    logger.info(account.getUserName() + "登录失败！");
                    channel.close().sync();
                } else {
                    responseService.loginResponse(channel, ProtocolHeader.REQUEST_ERROR, "")
                            .addListener(new ChannelFutureListener() {
                                public void operationComplete(ChannelFuture future) throws Exception {
                                    if (future.isSuccess()) {
                                        logger.info(account.getUserName() + "登录失败！");
                                        channel.close().sync();
                                    }
                                }
                            });
                }
            }
        });
    }


    public void logout(String body, Channel channel) {
        final Account account = (Account) deserializeBody(body, Account.class);
        ConnectionPool.remove(account.getToken());

        try {
            channel.close().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error(e);
        }
    }
}
